

import 'package:data_table_2/data_table_2.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import 'package:yuellyfactory/eventbus/EventBusUtil.dart';
import 'package:yuellyfactory/util/BaseRequest.dart';
import 'package:yuellyfactory/util/MathUtil.dart';
import 'package:yuellyfactory/views/dto/PriceParm.dart';
import 'package:yuellyfactory/views/purchase/MaterialChildListEditVC.dart';

import '../../eventbus/EventRefreshBase.dart';
import '../../util/ColorUtil.dart';
import '../../util/ToastUtil.dart';
import '../../util/ViewUtil.dart';
import '../../util/XNumberTextInputFormatter.dart';
import '../base/MaterialListEditVC.dart';
import '../base/MaterialListParmEditVC.dart';
import '../dto/PriceMaterial.dart';
import '../dto/PricePart.dart';
import 'dart:convert';
import '../dto/PriceRule.dart';

class MaterialItemView{
  final BuildContext context;
  final VoidCallback callback;

  final Map<String,bool> showMaps;

  final State state;

  // 固定高度参数（可根据需求调整）
  final double _headerHeight = 56; // 表头高度（含内边距）
  final double _rowHeight = 65; // 每行高度（含内边距）
  final double _borderWidth = 1; // 边框宽度
  final double _outerPadding = 10; // 表格外间距


  PricePart? pricePart;

  MaterialItemView(this.context, this.callback,this.state,this.showMaps);
  final dialogKey = GlobalKey<ShadFormState>();
  Widget getPartView(PricePart partData){
    pricePart=partData;

    return  Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: getMaterialView(partData),
    );
  }

  List<Widget> getMaterialView(PricePart partData){
    List<Widget>widgets=[];
    widgets.add(SizedBox(height: ViewUtil.screenHeight(10),));
    widgets.add(
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Expanded(child:  Wrap(
              crossAxisAlignment: WrapCrossAlignment.center,
              runAlignment: WrapAlignment.start,
              direction: Axis.horizontal, // 水平方向排列（默认）
              alignment: WrapAlignment.start, // 水平靠左（默认值，可省略）
              spacing: 10, // 子组件横向间距
              runSpacing: 0, // 换行后纵向间距
              children: getGlobalPara(partData),
            )),
            IconButton(icon:  Icon( getIsShow(partData.id)?Icons.keyboard_arrow_down_outlined:Icons.keyboard_arrow_right_outlined),
              color:ColorUtil.colorBlue,
              iconSize: ViewUtil.screenWidth(35),onPressed: (){
                bool result= getIsShow(partData.id);
                result=!result;
                showMaps[partData.id]=result;

                state.setState(() {

                });
              },),
            // ViewUtil.addIcon('添加品牌',(){
            //   getAllBrand(partData);
            // }),
            // ViewUtil.delIcon('删除配置',(){
            //   showDelDialog(partData);
            //
            // })
          ],
        )
       );
    //添加品牌
    for(PricePart brand in partData.materialList){
      widgets.add(Visibility(visible:getIsShow(partData.id) , child: brandItem(brand),));
    }
    widgets.add(ViewUtil.lineView());
    return widgets;
  }

  Widget brandItem(PricePart partData){
    List<Widget> widgets=[];
    widgets.add(Row(
      children: [
        SizedBox(width: ViewUtil.screenWidth(10),),
        Text('品牌 : ${partData.name}',style: TextStyle(fontSize: ViewUtil.fontSize(22),fontWeight: FontWeight.bold),),
        SizedBox(width: ViewUtil.screenWidth(20),),
        Expanded(child: Container()),
        IconButton(icon:  Icon( getIsShow(partData.id)?Icons.keyboard_arrow_down_outlined:Icons.keyboard_arrow_right_outlined),
          color:ColorUtil.colorBlue,
          iconSize: ViewUtil.screenWidth(35),onPressed: (){
            bool result= getIsShow(partData.id);
            result=!result;
            showMaps[partData.id]=result;
            state.setState(() {
            });
          },),
        // ViewUtil.addIcon('添加系列',(){
        //   //添加系列
        //   getSerialList(partData);
        //
        // }),
        // ViewUtil.delIcon('删除配置',(){
        //   showDelDialog(partData);
        // })
      ],
    ));
    for(PricePart serial in partData.materialList){

      widgets.add(Visibility(
          visible:getIsShow(partData.id),
          child: serialItem(serial)));
    }

    return Column(
      children: widgets,
    );
  }

  Widget serialItem(PricePart partData){

    List<Widget> widgets=[];
    widgets.add(Row(
      children: [
        SizedBox(width: ViewUtil.screenWidth(30),),
        Text('系列 : ${partData.name}',style: TextStyle(fontSize: ViewUtil.fontSize(22),fontWeight: FontWeight.bold),),
        SizedBox(width: ViewUtil.screenWidth(20),),
        Expanded(child: Container()),
        IconButton(icon:  Icon( getIsShow(partData.id)?Icons.keyboard_arrow_down_outlined:Icons.keyboard_arrow_right_outlined),
          color:ColorUtil.colorBlue,
          iconSize: ViewUtil.screenWidth(35),onPressed: (){
            bool result= getIsShow(partData.id);
            result=!result;
            showMaps[partData.id]=result;
            state.setState(() {
            });
          },),
        // ViewUtil.addIcon('添加型号',(){
        //   //添加系列
        //   getAllMaterial(partData);
        // }),
        // ViewUtil.delIcon('删除配置',(){
        //   showDelDialog(partData);
        // })
      ],
    ));
    for(PricePart material in partData.materialList){

      widgets.add(Visibility(
          visible: getIsShow(partData.id),
          child: Card(
            color: Colors.white,
            child: partItemView(material),
          )));
    }

    return Column(
      children: widgets,
    );
  }

  Widget partItemView(PricePart material){
    List<Widget> widgets=[];

    widgets.add(Row(
      children: [
        SizedBox(width: ViewUtil.screenWidth(40),),
        Text('${material.name}',style: TextStyle(fontSize: ViewUtil.fontSize(22),fontWeight: FontWeight.bold),),
        SizedBox(width: ViewUtil.screenWidth(20),),
        const SizedBox(width: 20),
         
        Expanded(child: Wrap(
          crossAxisAlignment: WrapCrossAlignment.center,
          children: [

            Text(
              'Code：${material.code}',
              style: TextStyle(fontSize: ViewUtil.fontSize(18)),
            ),

            const SizedBox(width: 20),
            Text(
              '数量：${MathUtil.formatDouble(material.count, 2)}',
              style: TextStyle(fontSize: ViewUtil.fontSize(18)),
            ),
            const SizedBox(width: 20),
            Text(
              '单价：${MathUtil.formatDouble(material.price, 2)}元',
              style: TextStyle(fontSize: ViewUtil.fontSize(18)),
            ),
            const SizedBox(width: 20),
            Text(
              '总价：${MathUtil.formatDouble(material.totalPrice, 2)}元',
              style: TextStyle(fontSize: ViewUtil.fontSize(18)),
            ),
            const SizedBox(width: 20),
            Text(
              '型号说明：${getPartSpec(material)}',
              style: TextStyle(fontSize: ViewUtil.fontSize(18)),
            ),


          ],
        )),
        IconButton(icon:  Icon( getIsShow(material.id)?Icons.keyboard_arrow_down_outlined:Icons.keyboard_arrow_right_outlined),
          color:ColorUtil.colorBlue,
          iconSize: ViewUtil.screenWidth(35),onPressed: (){
            bool result= getIsShow(material.id);
            result=!result;
            showMaps[material.id]=result;
            state.setState(() {
            });
          },),
        // ViewUtil.delIcon('删除配置',(){
        //   showDelDialog(material);
        // })
        ViewUtil.configIcon("更换配置", (){
          getCanChangePart(material);
        })
      ],
    ));

    widgets.add( Visibility(
        visible: getIsShow(material.id),
        child: Padding(padding: EdgeInsets.only(left: ViewUtil.screenWidth(30)),
      child: Wrap(
        crossAxisAlignment: WrapCrossAlignment.center,
        runAlignment: WrapAlignment.start,
        direction: Axis.horizontal, // 水平方向排列（默认）
        alignment: WrapAlignment.start, // 水平靠左（默认值，可省略）
        spacing: 10, // 子组件横向间距
        runSpacing: 0, // 换行后纵向间距
        children: paramView(material),
      ),)));

    if(material.childMaterialList.isNotEmpty){
      var tableHeight=_calculateTableHeight(material.childMaterialList.length);
      widgets.add(
          Visibility(
          visible: getIsShow(material.id),
          child:
          Container(
            // 应用计算出的高度
            alignment: Alignment.centerLeft,
            margin: EdgeInsets.only(left: ViewUtil.screenWidth(35),right: ViewUtil.screenWidth(10),bottom: ViewUtil.screenHeight(10)),
            height: tableHeight>400?400:tableHeight,
            decoration: BoxDecoration(
              border: Border.all(color: Colors.grey[200]!, width: _borderWidth),
              borderRadius: BorderRadius.circular(8),
            ),
            child: DataTable2(
              columnSpacing: 12,
              horizontalMargin: 12,
              minWidth: 4000,
              isHorizontalScrollBarVisible:true,
              headingRowHeight: _headerHeight - 2 * _borderWidth, // 减去边框占用高度
              dataRowHeight: _rowHeight - 2 * _borderWidth, // 减去边框占用高度
              // 表头
              columns: getTableHead(material),

              // 表格内容（行高固定）
              rows: material.childMaterialList.map((item) {
                return DataRow(cells: getTableItem(material,item));
              }).toList(),
            ),
          )
      )
      );
    }
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: widgets,);
  }




  List<DataColumn2> getTableHead(PricePart material){
    List<DataColumn2> widgets=[];
    widgets.add(const DataColumn2(
      label: Text('￥单价'),
      fixedWidth: 100,
    ),);
    for(var i=0;i<material.childParmList.length;i++){
      var item=material.childParmList[i];
      if(i!=material.childParmList.length-1){
        widgets.add(DataColumn2(label: Text(item.name+getParmUnit(item)),fixedWidth: 100,));

      }else{
        widgets.add(DataColumn2(label: Text(item.name+getParmUnit(item)),fixedWidth: 500,));
      }

    }

    return widgets;
  }

  

  getParmUnit(PriceParm item){
    if(item.unit!=null&&item.unit.isNotEmpty){
      return "(${item.unit})";
    }else{
      return "";
    }
  }

  List<DataCell> getTableItem(PricePart partData,PriceMaterial material){
    List<DataCell> widgets=[];

    widgets.add(DataCell(Padding(
      padding: const EdgeInsets.symmetric(vertical: 12),
      child: Text(MathUtil.formatDouble(material.price, 2)),
    )));
    for(var item in partData.childParmList){
      widgets.add(DataCell(Padding(
        padding: const EdgeInsets.symmetric(vertical: 12),
        child:

            GestureDetector(
              onTap: (){
                showShadSheet(
                  barrierColor: Colors.transparent,
                  side: ShadSheetSide.right,
                  context: context,
                  builder: (context) =>   MaterialChildListEditVC(pricePart:partData ,priceMaterial: material, callback: () {
                    //回调
                  }, priceModel: pricePart!,),
                );
              },
              child: Text(getParmValue(item.id,material.data)),
            ),
      )));
    }

    return widgets;
  }

  getParmValue(String id,var data){
    if(data==null||data.length==0)return "";
    List datas=json.decode(data);
    var values={};
    for(var item in datas){
      values[item["id"]]=item["value"];
    }

    String value="";
    if(values.containsKey(id)){
      value=values[id].toString();
    }
    bool isNum=MathUtil.isNumeric(value);
    return isNum?MathUtil.formatDouble(double.parse(value), 2):value;
  }

  // 计算表格总高度的核心方法
  double _calculateTableHeight(int length) {
    // 总高度 = 表头高度 + 数据行总高度 + 边框总高度
    // 边框高度：上下边框（2条）+ 行之间的分隔线（数据行数-1条）
    final int borderCount = 2 + (length - 1);
    final double totalBorderHeight = borderCount * _borderWidth;

    return _headerHeight + // 表头高度
        (_rowHeight * length) + // 所有数据行高度
        totalBorderHeight; // 边框总高度
  }




  List<Widget> paramView(PricePart material){
    List<Widget> widgets=[];
    for(PriceParm parm in material.parmList){
      widgets.add(SizedBox(width: 140,
        child:
        ShadInput(
          prefix: Text(parm.name),
          suffix: Text(parm.unit??""),
          textAlign: TextAlign.end,
          placeholder: Text("请输入${parm.name}"),

          enabled: parm.handle==0,
          onPressedOutside: (value){

          },
          onEditingComplete: (){
            updateValue(parm);
          },
          initialValue: parm.handle==0? (parm.value.isNotEmpty?parm.value.toString():""):getRuleString(parm.rule),
          onChanged: (value){
            debugPrint(value);
            parm.value=value;

          },
        ),));
    }
    return widgets;
  }


   checkHasUseParm(String rule,List globalParm,Map<String,PriceParm> canShow){
      for(PriceParm parm in globalParm){
        if(rule.contains(parm.id)){
          if(!canShow.containsKey(parm.id)){
            canShow[parm.id]=parm;
          }
        }
      }
   }

  List<Widget> getGlobalPara(PricePart partData){

    //获取需要添加的全局变量
    List<PricePart> allPricePart=[];
    for(PricePart brand in partData.materialList){
      for(PricePart serial in brand.materialList){
        for(PricePart part in serial.materialList){
          allPricePart.add(part);
        }
      }
    }

   Map<String,PriceParm> canShow={};

    for(PricePart part in allPricePart){
      String materialRule= part.materialRule;
      String rule=part.rule;
      for(PriceParm parm in part.childParmList){
        String childRule=parm.rule;
        if(childRule.isNotEmpty){
          checkHasUseParm(childRule, partData.parmList, canShow);
        }
      }
      checkHasUseParm(rule, partData.parmList, canShow);
      checkHasUseParm(materialRule, partData.parmList, canShow);
    }

    List<PriceParm> newParms=[];
    for (var value in canShow.values) {
      newParms.add(value);
    }


    List<Widget> widgets=[];
    widgets.add( Text(
      partData.name,
      style: TextStyle(fontSize: ViewUtil.fontSize(22),fontWeight: FontWeight.bold),
    ),);

    widgets.add( Text(
      '单价:',
      style: TextStyle(fontSize: ViewUtil.fontSize(18)),
    ));
    widgets.add( Text(
      '${MathUtil.formatDouble(partData.price, 2)}元',
      style: TextStyle(fontSize: ViewUtil.fontSize(18)),
    ),);


    if(newParms.isNotEmpty){
      widgets.add(const SizedBox(width: 16));
      widgets.add( Text(
        '变动实价：',
        style: TextStyle(fontSize: ViewUtil.fontSize(18)),
      ));
      for(PriceParm parm in newParms){
        widgets.add(

            SizedBox(width: 180,
                child:
                ShadInput(
                  suffix: Text(parm.unit??""),
                  prefix: Text("${parm.name}:"),
                  textAlign: TextAlign.end,
                  enabled: parm.handle==0,
                  initialValue: parm.handle==0? (parm.value.isNotEmpty?parm.value.toString():""):getRuleString(parm.rule),
                  placeholder: Text("请输入${parm.name}"),
                  onChanged: (value){
                    debugPrint(value);
                    parm.value=value;
                    updateValue(parm);
                  },
                )));
      }
    }


    return widgets;
  }

  getRuleString(var rule){
    var ruleStr="";
    if(rule.isNotEmpty){
      List<dynamic> list = json.decode(rule);
      for(var item in list){
        PriceRule rule=PriceRule.fromJson(item);
        if(rule.handle==0){
          ruleStr="$ruleStr${rule.value}";
        }else{
          ruleStr="$ruleStr${rule.name}";
        }
      }
    }

    return ruleStr;
  }




  void showDelDialog(PricePart material){
    showShadDialog(
      context: context,
      builder: (context) => ShadDialog.alert(
        title: Text('确定要删除${material.name}吗?'),
        description: const Padding(
          padding: EdgeInsets.only(bottom: 8),
          child: Text(
            '点击删除将取消配置',
          ),
        ),
        actions: [
          ShadButton.outline(
            child: const Text('取消'),
            onPressed: () => Navigator.of(context).pop(false),
          ),
          ShadButton(
            child: const Text('删除'),
            onPressed: () {
              requestDelMaterial(material);
            },
          ),
        ],
      ),
    );
  }


  void requestDelMaterial(PricePart material){
    var parm={
      "id":material.configId
    };
    BaseRequest.postHttp('price/delconfigpart',parameters: parm, canTip: true, context: context, onSuccess: (data){
      bool result = BaseRequest.chekResponse(data, true);
      if (result) {
        ToastUtil.showToast("删除成功");
        eventBus.fire(EventRefreshBase());
        Navigator.pop(context);
      }
    }, onError: (error){});
  }

  void updateValue(PriceParm parm){
   var parms={
     "id":parm.id,
     "value":parm.value
   };
    BaseRequest.postHttp('price/editparmvalue',parameters: parms, canTip: false, context: context, onSuccess: (data){
      //countPrice();
      eventBus.fire(EventRefreshBase());
    }, onError: (error){});
  }



  void getAllMaterial(PricePart partData){
    var parm={
      "id":partData.id
    };
    BaseRequest.postHttp('price/baseallserialmaterial',parameters: parm, canTip: true , context: context, onSuccess: (data){
      bool result = BaseRequest.chekResponse(data, true);
      if (result) {
        dynamic datas = data["data"];
        var items={};
        for (var i = 0; i < datas.length; i++) {
          var item = datas[i];
          var id=item["id"];
          var name=item["name"];
          items[id]=name;
        }
        addMatterialDialog(items,partData);
      }
    }, onError: (error){

    });
  }

  void addMatterialDialog(var options,PricePart part) {
    //选择零件列表。
    showShadDialog(context: context, builder: (context) =>
        ShadDialog(
            actions: [ShadButton(child: Text('确定'), onPressed: () {
              submitAddMaterial(part);
            },)
            ],
            child:
            ShadForm(
                key: dialogKey,
                child:
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    ShadSelectFormField<String>(
                      id: 'material',
                      label: const Text('材料'),
                      minWidth: 350,
                      options: (options as Map).entries
                          .map((e) => ShadOption(value: e.key.toString(), child: Text(e.value.toString())))
                          .toList(), // 注意添加toList()转换
                      selectedOptionBuilder: (context, value) {
                        if (value == null || value == 'none') {
                          return const Text('请选择材料');
                        }
                        // 使用空值合并运算符??代替!，提供默认值
                        return Text((options as Map)[value]?.toString() ?? '未知选项');
                      },
                      placeholder: const Text('请选择材料'),
                      validator: (v) {
                        if (v == null) {
                          return '请选择材料';
                        }
                        return null;
                      },
                    ),
                    const SizedBox(height: 10),
                    ShadInputFormField(
                      id: 'count',
                      initialValue: "1",
                      keyboardType: TextInputType.numberWithOptions(decimal: true),
                      inputFormatters: [
                        FilteringTextInputFormatter.allow(RegExp("[0-9.]")),
                        XNumberTextInputFormatter(
                            maxIntegerLength: null,
                            maxDecimalLength: 2,
                            isAllowDecimal: true),
                      ],
                      label: const Text('数量'),
                      placeholder: const Text('请输入数量'),
                      validator: (v) {
                        if (v.isEmpty) {
                          return '请输入数量';
                        }
                        return null;
                      },
                    ),
                  ],
                )

            )

        )
    );

  }

  void submitAddMaterial(PricePart partData){
    if (dialogKey.currentState!.saveAndValidate()) {
      var values = dialogKey.currentState!.value;
      var material = values["material"];
      var count=values["count"];
      var parm={
        "modelId":pricePart!.modelId,
        "partId":material,
        "parentId":partData.configId,
        "count":count,
        "type":"part"
      };
      BaseRequest.postHttp('price/addconfigpart',parameters: parm, canTip: true, context: context, onSuccess: (data){
        bool result = BaseRequest.chekResponse(data, true);
        if (result) {
          ToastUtil.showToast("添加成功");
          eventBus.fire(EventRefreshBase());
          Navigator.pop(context);
        }
      }, onError: (error){});
    }
  }

  void getAllBrand(PricePart partData){
    var parm={
      "id":partData.id
    };
    BaseRequest.postHttp('price/baseallbrand',parameters: parm, canTip: true , context: context, onSuccess: (data){
      bool result = BaseRequest.chekResponse(data, true);
      if (result) {
        dynamic datas = data["data"];
        var items={};
        for (var i = 0; i < datas.length; i++) {
          var item = datas[i];
          var id=item["id"];
          var name=item["name"];
          items[id]=name;
        }
        addBrandDialog(items,partData);

      }
    }, onError: (error){

    });
  }

  void addBrandDialog(var options,PricePart part) {
    //选择品牌列表。
    showShadDialog(context: context, builder: (context) =>
        ShadDialog(
            actions: [ShadButton(child: Text('确定'), onPressed: () {
              submitAddBrand(part);
            },)
            ],
            child:
            ShadForm(
                key: dialogKey,
                child:
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    ShadSelectFormField<String>(
                      id: 'brand',
                      label: const Text('品牌'),
                      minWidth: 350,
                      options: (options as Map).entries
                          .map((e) => ShadOption(value: e.key.toString(), child: Text(e.value.toString())))
                          .toList(), // 注意添加toList()转换
                      selectedOptionBuilder: (context, value) {
                        if (value == null || value == 'none') {
                          return const Text('请选择品牌');
                        }
                        // 使用空值合并运算符??代替!，提供默认值
                        return Text((options as Map)[value]?.toString() ?? '未知选项');
                      },
                      placeholder: const Text('请选择品牌'),
                      validator: (v) {
                        if (v == null) {
                          return '请选择品牌';
                        }
                        return null;
                      },
                    ),
                  ],
                )

            )

        )
    );

  }

  void submitAddBrand(PricePart partData){
    if (dialogKey.currentState!.saveAndValidate()) {
      var values = dialogKey.currentState!.value;
      var material = values["brand"];

      var parm={
        "modelId":pricePart!.modelId,
        "partId":material,
        "parentId":partData.configId,
        "type":"brand",
        "count":0,
      };
      BaseRequest.postHttp('price/addconfigpart',parameters: parm, canTip: true, context: context, onSuccess: (data){
        bool result = BaseRequest.chekResponse(data, true);
        if (result) {
          ToastUtil.showToast("添加成功");
          eventBus.fire(EventRefreshBase());
          Navigator.pop(context);
        }
      }, onError: (error){});
    }
  }

  void addSerialDialog(var options,PricePart part) {
    //选择品牌列表。
    showShadDialog(context: context, builder: (context) =>
        ShadDialog(
            actions: [ShadButton(child: Text('确定'), onPressed: () {
              submitAddSerial(part);
            },)
            ],
            child:
            ShadForm(
                key: dialogKey,
                child:
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    ShadSelectFormField<String>(
                      id: 'serial',
                      label: const Text('系列'),
                      minWidth: 350,
                      options: (options as Map).entries
                          .map((e) => ShadOption(value: e.key.toString(), child: Text(e.value.toString())))
                          .toList(), // 注意添加toList()转换
                      selectedOptionBuilder: (context, value) {
                        if (value == null || value == 'none') {
                          return const Text('请选择系列');
                        }
                        // 使用空值合并运算符??代替!，提供默认值
                        return Text((options as Map)[value]?.toString() ?? '未知选项');
                      },
                      placeholder: const Text('请选择系列'),
                      validator: (v) {
                        if (v == null) {
                          return '请选择系列';
                        }
                        return null;
                      },
                    ),
                  ],
                )

            )

        )
    );

  }

  void submitAddSerial(PricePart partData){
    if (dialogKey.currentState!.saveAndValidate()) {
      var values = dialogKey.currentState!.value;
      var material = values["serial"];

      var parm={
        "modelId":pricePart!.modelId,
        "partId":material,
        "parentId":partData.configId,
        "type":"serial",
        "count":0,
      };
      BaseRequest.postHttp('price/addconfigpart',parameters: parm, canTip: true, context: context, onSuccess: (data){
        bool result = BaseRequest.chekResponse(data, true);
        if (result) {
          ToastUtil.showToast("添加成功");
          eventBus.fire(EventRefreshBase());
          Navigator.pop(context);
        }
      }, onError: (error){});
    }
  }

  void getSerialList(PricePart partData){
    var parm={
      "id":partData.id
    };
    BaseRequest.postHttp('price/baseallserial',parameters: parm, canTip: true , context: context, onSuccess: (data){
      bool result = BaseRequest.chekResponse(data, true);
      if (result) {
        dynamic datas = data["data"];
        var items={};
        for (var i = 0; i < datas.length; i++) {
          var item = datas[i];
          var id=item["id"];
          var name=item["name"];
          items[id]=name;
        }
        addSerialDialog(items,partData);

      }
    }, onError: (error){

    });
  }

    void getCanChangePart(PricePart partData){
      var parm={
        "partId":partData.id,
        "modelId":pricePart!.modelId,
      };
      BaseRequest.postHttp('price/getcanchangepart',parameters: parm, canTip: true , context: context, onSuccess: (data){
        bool result = BaseRequest.chekResponse(data, true);
        if (result) {
          dynamic datas = data["data"];
          var items={};
          for (var i = 0; i < datas.length; i++) {
            var item = datas[i];
            var id=item["id"];
            var name=item["name"];
            items[id]=name;
          }
          if(items.isEmpty){
            ToastUtil.showToast("暂无可换配置，请先配置");
          }else{
            changePartDialog(items, partData);
          }

        }
      }, onError: (error){

      });


    }


  void changePartDialog(var options,PricePart part) {
    //选择品牌列表。
    showShadDialog(context: context, builder: (context) =>
        ShadDialog(
            actions: [ShadButton(child: Text('确定'), onPressed: () {
              submitChangePart(part);
            },)
            ],
            child:
            ShadForm(
                key: dialogKey,
                child:
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    ShadSelectFormField<String>(
                      id: 'part',
                      label: const Text('型号'),
                      minWidth: 350,
                      options: (options as Map).entries
                          .map((e) => ShadOption(value: e.key.toString(), child: Text(e.value.toString())))
                          .toList(), // 注意添加toList()转换
                      selectedOptionBuilder: (context, value) {
                        if (value == null || value == 'none') {
                          return const Text('请选择型号');
                        }
                        // 使用空值合并运算符??代替!，提供默认值
                        return Text((options as Map)[value]?.toString() ?? '未知选项');
                      },
                      placeholder: const Text('请选择型号'),
                      validator: (v) {
                        if (v == null) {
                          return '请选择型号';
                        }
                        return null;
                      },
                    ),
                  ],
                )

            )

        )
    );

  }


  void submitChangePart(PricePart partData){
    if (dialogKey.currentState!.saveAndValidate()) {
      var values = dialogKey.currentState!.value;
      var newId = values["part"];

      var parm={
        "modelId":pricePart!.modelId,
        "oldId":partData.id,
        "newId":newId,

      };
      BaseRequest.postHttp('price/changeconfigpart',parameters: parm, canTip: true, context: context, onSuccess: (data){
        bool result = BaseRequest.chekResponse(data, true);
        if (result) {
          ToastUtil.showToast("更换成功");
          eventBus.fire(EventRefreshBase());
          Navigator.pop(context);
        }
      }, onError: (error){});
    }
  }



  getRuleValue(var rule,Map allValue){
    var ruleStr="";
    if(rule.isNotEmpty){
      List<dynamic> list = json.decode(rule);
      for(var item in list){
        PriceRule rule=PriceRule.fromJson(item);
        if(rule.handle==0){
          ruleStr="$ruleStr${rule.value}";
        }else{
          if(allValue.containsKey(rule.value)){
            ruleStr="$ruleStr${allValue[rule.value]}";
          }else{
            return 0;
          }

        }
      }
    }

    return MathUtil.countExpression(ruleStr);
  }

  void countPrice(){
    //先计算全局参数
    Map allValue={};
    if(pricePart==null)return;
    //先计算一遍普通值
    for(PriceParm parm in pricePart!.parmList){
      if(parm.handle==0){
        allValue[parm.id]=parm.value;
      }
    }
    for(PriceParm parm in pricePart!.parmList){
      if(parm.handle==1){
         var value=getRuleValue(parm.rule, allValue);
         allValue[parm.id]=value;
      }
    }
    //计算每一个材料参数
    for(PricePart material in pricePart!.materialList){
           var parmList= material.parmList;
           for(PriceParm parm in parmList){
             if(parm.handle==0){
               allValue[parm.id]=parm.value;
             }
           }
           for(PriceParm parm in parmList){
             if(parm.handle==1){
               var value=getRuleValue(parm.rule, allValue);
               allValue[parm.id]=value;
             }
           }
    }

    double totalPrice=0;
    for(PricePart material in pricePart!.materialList){
      var rule=material.rule;
      var value=getRuleValue(rule, allValue);
      material.price=double.parse('$value');
      material.totalPrice=material.count*material.price;
      totalPrice=totalPrice+material.totalPrice;
    }
    pricePart!.price=totalPrice;


  }

  getIsShow(String id){
    bool result=false;
    if(showMaps.containsKey(id)){
      return showMaps[id];
    }
    return result;
  }
  getPartSpec(PricePart partData){
    var spec=partData.spec;
    var value="";
    if(spec.isNotEmpty){
      var  specsList=jsonDecode(spec);
      for(var item in specsList){
        var str="${item["name"]}:${item["value"]}";
        value="$value$str | ";
      }
    }

    return value;
  }


}